#include "../include/head.h"

void *pthread_enter(void *arg)
{
    shareRes_t *share = (shareRes_t *)arg;

    int *clientInfo = share->pclient_info;
    pthread_mutex_t* mtx_clientInfo = share->mutex_client_info;
    pthread_mutex_t* mtx_taskQueue = share->mutex_taskqueue;
    pthread_cond_t* cond_taskQueue = share->cond;
    taskQueue_t* taskQueue = &share->taskqueue;
    int* exitFlag = share->exitflag ;

    RequestPackage* sharedPackage = (RequestPackage*)calloc(1,sizeof(RequestPackage));
    while(1)
    {
        pthread_mutex_lock(mtx_taskQueue);

        while(*exitFlag!=1 && taskQueue->queuesize==0)
        {
            pthread_cond_wait(cond_taskQueue,mtx_taskQueue);
        }
        if(*exitFlag == 1)
        {
            free(sharedPackage);
            pthread_mutex_unlock(mtx_taskQueue);
            pthread_exit(NULL);
        }
        
       // printf("before thread delete %p size:%p -  %d\n",taskQueue,&taskQueue->queuesize,taskQueue->queuesize);
        taskNode_t* node = head_delete(taskQueue);        
        //printf("after thread delete %p size:%p - %d\n",taskQueue,&taskQueue->queuesize,taskQueue->queuesize);
        pthread_mutex_unlock(mtx_taskQueue);


        pthread_mutex_lock(mtx_clientInfo);
        int clientid = clientInfo[node->netfd];
        if(clientid == -1 || clientid!=node->client_id)
        {
            
            pthread_mutex_unlock(mtx_clientInfo);
            free(node);
            continue;
        }
        pthread_mutex_unlock(mtx_clientInfo);

        sharedPackage->type = node->type;

        sharedPackage->vir_path_len = strlen(node->virtualPath);
        memcpy(sharedPackage->vir_path_val, node->virtualPath, sharedPackage->vir_path_len);

        // printf("package vp:%s node vp:%s\n",sharedPackage->vir_path_val,node->virtualPath);
        sharedPackage->args_len = strlen(node->args);
        memcpy(sharedPackage->args_val, node->args, sharedPackage->args_len);
        //printf("enter:%d\n", node->netfd);
        //printf("enter:%d\n", node->type);
        pthread_func(node, sharedPackage);
        // printf("回到入口\n");
        memset(sharedPackage,0,sizeof(RequestPackage));

        free(node);
    }
}
